import 'dart:io';

import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:in_app_purchase_storekit/in_app_purchase_storekit.dart';
import 'package:in_app_purchase_storekit/store_kit_wrappers.dart';
import 'package:ylm_ui_kit/ylm_ui_kit.dart';

class SeIapService {
  static final SeIapService _instance = SeIapService._internal();
  factory SeIapService() => _instance;
  SeIapService._internal();

  final InAppPurchase _inAppPurchase = InAppPurchase.instance;
  List<ProductDetails> _products = [];

  Future<void> _initStoreInfo() async {
    if (Platform.isIOS) {
      var iosPlatformAddition = _inAppPurchase.getPlatformAddition<InAppPurchaseStoreKitPlatformAddition>();
      await iosPlatformAddition.setDelegate(_SePaymentQueueDelegate());
    }
  }

  Future applePay({required String productId, required String orderNum}) async {
    if (productId.empty) return;

    /// _inAppPurchase是否有效
    final bool isAvailable = await _inAppPurchase.isAvailable();
    if (!isAvailable) {
      return;
    }

    /// 如果是iOS设备进行设置代理，接口苹果服务器的回调。
    if (Platform.isIOS) await _initStoreInfo();

    /// 查询后台返回的ProductId是否在苹果服务器上注册了
    final ProductDetailsResponse productDetailResponse = await _inAppPurchase.queryProductDetails({productId});

    /// 查询不到说明没注册
    if (productDetailResponse.error != null || productDetailResponse.productDetails.isEmpty) {
      Loading.toast('No product found', closeLoading: true);
      return;
    }

    _products = productDetailResponse.productDetails;

    /// 查询成功
    ProductDetails productDetails = _products[0];

    final PurchaseParam purchaseParam = PurchaseParam(
      productDetails: productDetails,
      applicationUserName: orderNum,
    );

    /// 向苹果服务器发起支付请求
    _inAppPurchase.buyConsumable(purchaseParam: purchaseParam);
  }

  void completePurchase(PurchaseDetails purchaseDetails) {
    _inAppPurchase.completePurchase(purchaseDetails);
  }
}

class _SePaymentQueueDelegate implements SKPaymentQueueDelegateWrapper {
  @override
  bool shouldContinueTransaction(SKPaymentTransactionWrapper transaction, SKStorefrontWrapper storefront) {
    return true;
  }

  @override
  bool shouldShowPriceConsent() {
    return false;
  }
}
